<?php
/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2017/3/14
 * Time: 10:28
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Cate;
use common\models\datas\Customer;
use common\models\datas\Student;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use yii\web\Response;

class TeacherappointController extends ActiveController{
    public $modelClass = 'zhtfrontend\models\datas\OrdersItems';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items'
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find()->where(['type' => 0]);
        return new ActiveDataProvider([
            'query' => $query
        ]);
    }

    //教师端我的预约
    public function actionTeacherappointment(){
        $user_id = \Yii::$app->request->get('user_id');
        $sub_cate_id = \Yii::$app->request->get('sub_cate_id');
        $admin = Admin::findOne(['id'=>$user_id]);
        $data = [];
        if(!empty($admin) && !empty($admin->teacher_id)){
            $teacher_id = $admin->teacher_id;
            if($admin['role'] == 'class_teacher'){
                $teacher_ids = (new Query())->select('id')->from('{{%teacher}}')->where(['parent_id'=>$teacher_id])->column(Fun::getSiteDb());
            }
            if(!in_array($sub_cate_id,[9991,9992,9993])){//当属于艺教学数组的时候不要计算分店的
                $goods_arr_sql = (new Query())->select(["goods_id","max(IF(name='最满人数',value,'')) as max_number","max(IF(obj_type='teacher',attribute_id,'')) as teacher_id"])
                    ->distinct()->from('{{%goods_attr}}')
                    ->groupBy('goods_id');//->having(['teacher_id'=>$teacher_id])->all(Fun::getSiteDb());

                if($admin['role'] == 'class_teacher'){
                    //$teacher_ids = (new Query())->select('id')->from('{{%teacher}}')->where(['parent_id'=>$teacher_id])->column(Fun::getSiteDb());
                    $goods_query = (new Query())->select('goodsarr.*,g.cat_id')->from(['goodsarr'=>$goods_arr_sql])->leftJoin('{{%goods}} g','goodsarr.goods_id=g.id')->where(['goodsarr.teacher_id'=>$teacher_ids]);
                }else{
                    $goods_query = (new Query())->select('goodsarr.*,g.cat_id')->from(['goodsarr'=>$goods_arr_sql])->leftJoin('{{%goods}} g','goodsarr.goods_id=g.id')->where(['goodsarr.teacher_id'=>$teacher_id]);
                }
                if($sub_cate_id != 'undefined' && !empty($sub_cate_id)){
                    $category_all = Fun::cache('CateGoodsCourse_cache',false);
                    $cat_ids = array_keys($category_all);
                    $category = Cate::findOne(['id' => $sub_cate_id]);
                    $category_childs = $category['arrchild_id'];
                    $category_childsarr = explode(",", $category_childs);
                    foreach ($category_childsarr as $k => $vv) {
                        if (!in_array($vv, $cat_ids)) {
                            unset($category_childsarr[$k]);
                        }
                    }
                    $goods_query->andWhere(['in','g.cat_id',$category_childsarr]);
                }
                $goods_arrs = $goods_query->all(Fun::getSiteDb());
                if(!empty($goods_arrs)) {
                    foreach ($goods_arrs as $k => $goodarr) {
                        $goodid = $goodarr['goods_id'];
                        $good = Goods::find()->joinWith('goodsClassTime')->where(['id' => $goodid])->asArray()->one();
                        $good['max_number'] = $goodarr['max_number'];
                        $good['teacher_id'] = $goodarr['teacher_id'];
                        $cm = ClassManage::findOne(['associate_id' => $goodid, 'is_old' => 0,'type'=>1]);
                        if (!empty($cm)) {
                            $classmanage_id = $cm->class_id;
                            $classstudents = ClassStudent::find()->where(['class_manage_id' => $classmanage_id])->andWhere(['not', ['status' => 3]])->asArray()->all();
                            $good['appointed_studentnum'] = count($classstudents);
                            foreach ($classstudents as $k => $cstudent) {
                                $order = null;
                                $student_detail = null;
                                if (!empty($cstudent['order_sales_id'])) {
                                    //每个学员对应当前商品的订单详细
                                    $order = (new Query())->select('orders.created_at,orders_items.*')->from('{{%orders}} orders')
                                        ->leftJoin('{{%orders_items}} orders_items', 'orders.id = orders_items.orders_id')
                                        ->where(['orders_items.id' => $cstudent['order_sales_id']])
                                        ->one(Fun::getSiteDb());
                                    $classstudents[$k]['order'] = $order;
                                } else {
                                    $classstudents[$k]['order'] = null;
                                }

                                if (!empty($cstudent['student_id'])) {
                                    $student = Student::findOne($cstudent['student_id']);
                                    if (!empty($student)) {
                                        $student_detail = $student->toArray();
                                        $customer = Customer::findOne($student_detail['customer_id']);
                                        $student_detail['logo'] = isset($customer['logo']) && !empty($customer['logo']) ? $customer['logo'] : null;
                                        $classstudents[$k]['student_detail'] = $student_detail;
                                    } else {
                                        $student_detail['logo'] = null;
                                        $classstudents[$k]['student_detail'] = $student_detail;
                                    }

                                } else {
                                    $classstudents[$k]['student_detail'] = null;
                                }
                            }
                            $good['class_students'] = $classstudents;
                        }
                        $data[] = $good;
                    }
                }
            }
//            print_r($data);exit;
            //以上是正常的课程或技教学的预约，关于艺教学的预约信息获取
            if($sub_cate_id == 'undefined' || in_array($sub_cate_id,[9991,9992,9993])){
                if($admin['role'] == 'class_teacher'){
                    $teacher_idarr = $teacher_ids;
                }else{
                    $teacher_idarr = $teacher_id;
                }
                $arrangements_query = (new Query())->select(['ar.art_teaching_id as art_teaching_id','a.class_count as class_count','at.star_time as start_time','at.end_time as end_time','at.class_day as class_day','c.*'])
                    ->from('{{%art_relation}} ar')
                    ->leftJoin('{{%art_teaching}} at','at.id = ar.art_teaching_id')
                    ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
                    ->leftJoin('{{%course}} c','c.id = a.course_id')
                    ->where(['a.teacher_id'=>$teacher_idarr]);
                if(in_array($sub_cate_id,[9991,9992,9993])){
                    switch ($sub_cate_id){
                        case 9991:
                            $type_value = 1;
                            break;
                        case 9992:
                            $type_value = 2;
                            break;
                        case 9993:
                            $type_value = 3;
                            break;
                        default:
                            $type_value = 1;
                            break;
                    }
                    $arrangements_query = $arrangements_query->andWhere(['c.type_id'=>$type_value]);
                }

                $arrangements = $arrangements_query->orderBy('ar.lesson ASC')
                    ->all(Fun::getSiteDb());
                if(!empty($arrangements)){
                    foreach ($arrangements as $arrangement){
                        //$good = Goods::find()->joinWith('goodsClassTime')->where(['id' => $goodid])->asArray()->one();
                        $good = [];
                        $good['name'] = $arrangement['name'];
                        $good['goodsClassTime'][] = ['class_day'=>$arrangement['class_day'],'start_time'=>$arrangement['start_time'],'end_time'=>$arrangement['end_time']];
                        $good['max_number'] = $arrangement['class_count'];
                        $good['teacher_id'] = $arrangement['art_teaching_id'];
                        $cm = ClassManage::findOne(['associate_id' => $arrangement['art_teaching_id'], 'is_old' => 0,'type'=>2]);
                        if (!empty($cm)) {
                            $classmanage_id = $cm->class_id;
                            $classstudents = ClassStudent::find()->where(['class_manage_id' => $classmanage_id])->andWhere(['not', ['status' => 3]])->asArray()->all();
                            $good['appointed_studentnum'] = count($classstudents);
                            foreach ($classstudents as $k => $cstudent) {
                                $order = null;
                                $student_detail = null;
                                if (!empty($cstudent['order_sales_id'])) {
                                    //每个学员对应当前商品的订单详细
                                    $order = (new Query())->select('orders.created_at,orders_items.*')->from('{{%orders}} orders')
                                        ->leftJoin('{{%orders_items}} orders_items', 'orders.id = orders_items.orders_id')
                                        ->where(['orders_items.id' => $cstudent['order_sales_id']])
                                        ->one(Fun::getSiteDb());
                                    $classstudents[$k]['order'] = $order;
                                } else {
                                    $classstudents[$k]['order'] = null;
                                }

                                if (!empty($cstudent['student_id'])) {
                                    $student = Student::findOne($cstudent['student_id']);
                                    if (!empty($student)) {
                                        $student_detail = $student->toArray();
                                        $customer = Customer::findOne($student_detail['customer_id']);
                                        $student_detail['logo'] = isset($customer['logo']) && !empty($customer['logo']) ? $customer['logo'] : null;
                                        $classstudents[$k]['student_detail'] = $student_detail;
                                    } else {
                                        $student_detail['logo'] = null;
                                        $classstudents[$k]['student_detail'] = $student_detail;
                                    }

                                } else {
                                    $classstudents[$k]['student_detail'] = null;
                                }
                            }
                            $good['class_students'] = $classstudents;
                        }
                        $data[] = $good;
                    }
                }
            }

        }
        //print_r($data);exit;
        return ['statusCode'=>200,'items'=>$data];
    }

    public function actionGetcate(){
        $category_all = Fun::cache('CateGoodsCourse_cache',false);
        //$tree_all = (new Tree($category_all))->get_tree_sleect_app_array();
        $tree_all = (new Tree($category_all))->get_tree_app_array();
        return ['statusCode'=>200,'message'=>'success','items'=>$tree_all];
    }
}